<script setup>
import userService from '@/api/modules/user.js'
import SvgIcon from '@/components/SvgIcon/SvgIcon.vue'
import useAppStore from '@/store/modules/app.js'
import { useUserStore } from '@/store/modules/user.js'
import { getToken } from '@/utils/auth.js'
import { useI18n } from 'vue-i18n'

const appStore = useAppStore()
const userStore = useUserStore()
const { t } = useI18n()
const title = import.meta.env.VITE_APP_TITLE
const loginFormRef = ref(null)
const loginForm = ref({
  username: '',
  password: '',
  uuid: '',
  code: '',
})
const loginRules = reactive({
  username: {
    required: true,
    message: t('please.enter', {
      name: t('login.username'),
    }),
  },
  password: {
    required: true,
    message: t('please.enter', {
      name: t('login.password'),
    }),
  },
  code: {
    required: true,
    message: t('please.enter', {
      name: t('login.code'),
    }),
  },
})

const registerForm = ref({
  username: '',
  email: '',
  nationality: null,
  password: '',
  account: '',
  confirmPassword: '',
  code: '',
})
const registerFormRef = ref(null)
const registerRules = reactive({
  username: {
    required: true,
    message: t('please.enter', {
      name: t('login.username'),
    }),
  },
  nationality: {
    required: true,
    message: t('please.select', {
      name: t('user.country'),
    }),
  },
  password: {
    required: true,
    message: t('please.enter', {
      name: t('login.password'),
    }),
  },
  confirmPassword: {
    required: true,
    validator: (rule, value, callback) => {
      if (value === '') {
        callback(new Error(t('login.confirmPassword')))
      }
      else if (value !== registerForm.value.password) {
        callback(new Error(t('login.passwordNotMatch')))
      }
      else {
        callback()
      }
    },
  },
  code: {
    required: true,
    message: t('please.enter', {
      name: t('login.code'),
    }),
  },
})

const codeImg = ref('')

const nationalityOptions = reactive([
  {
    value: 'zg',
    label: t('china'),
  },
  {
    value: 'alb',
    label: t('arab'),
  },
  {
    value: 'eg',
    label: t('russia'),
  },
  {
    value: 'fg',
    label: t('france'),
  },
  {
    value: 'xby',
    label: t('spain'),
  },
])
onMounted(() => {
  const token = getToken()
  if (!token) {
    getCaptchaImage()
  }
})

function getCaptchaImage() {
  userService.captchaImage().then((res) => {
    codeImg.value = `data:image/png;base64,${res.img}`
    loginForm.value.uuid = res.uuid
    registerForm.value.uuid = res.uuid
  })
}

function handleLogin(e) {
  e.preventDefault()
  loginFormRef.value?.validate((errors) => {
    if (!errors) {
      userService.login(loginForm.value).then(async (res) => {
        const setToken = await userStore.setToken(res.token)
        if (setToken) {
          userStore.getUserInfo()
          appStore.reloadPage()
          handleModalCancel()
        }
      }).catch((err) => {
        getCaptchaImage()
      })
    }
  })
}

function handleRegister(e) {
  e.preventDefault()
  registerFormRef.value?.validate((errors) => {
    if (!errors) {
      userService.register(registerForm.value).then((res) => {
        const code = res.code
        if (code === 200) {
          window.$dialog.success({
            title: t('message.registerSuccess'),
            content: t('login.reloginPrompt'),
            positiveText: t('button.confirm'),
            onPositiveClick: () => {
              handleSwitchType('login')
            },
          })
        }
      })
    }
  })
}
function handleModalCancel() {
  userStore.toggleAuthFormModal(false, 'login')
  loginForm.value = {}
  registerForm.value = {}
}

function handleSwitchType(val) {
  loginForm.value = {}
  registerForm.value = {}
  userStore.toggleAuthFormModal(true, val)
  getCaptchaImage()
}
</script>

<template>
  <n-modal
    v-model:show="userStore.authFormVisible"
    @after-leave="handleModalCancel"
  >
    <n-card
      :bordered="false" class="w-full max-w-lg"
      content-class="!p-0"
    >
      <div>
        <div class="flex flex-col p-6 space-y-1">
          <h3 class="font-semibold tracking-tight text-2xl text-center ">
            {{ userStore.authFormType === 'login' ? t('login.welcome') : t('login.registerAccount') }}
          </h3>
          <p class="text-sm text-muted-foreground text-center text-zinc-500 dark:text-zinc-400">
            {{ title }}
          </p>
        </div>
        <div class="p-6 pt-0 auth-form-container">
          <n-form
            v-if="userStore.authFormType === 'login'"
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            :show-label="false"
            :label-width="0"
            size="large"
          >
            <n-form-item
              path="username"
            >
              <n-input
                v-model:value="loginForm.username"
                :placeholder="t('please.enter', {
                  name: t('login.username'),
                })"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="lucide:user" class="relative top-[-1px] text-zinc-500" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item
              path="password"
            >
              <n-input
                v-model:value="loginForm.password"
                type="password"
                show-password-on="mousedown"
                :placeholder="t('please.enter', {
                  name: t('login.password'),
                })"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="lucide:lock" class="relative top-[-1px]  text-zinc-500" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="code">
              <n-input-group>
                <n-input
                  v-model:value="loginForm.code" :style="{ width: '80%' }" clearable :placeholder="t('please.enter', {
                    name: t('login.code'),
                  })"
                >
                  <template #prefix>
                    <SvgIcon name="lucide:shield" class="relative top-[-1px]  text-zinc-500" />
                  </template>
                </n-input>
                <div class="h-[40px] w-[26%] cursor-pointer" style="margin-left: 5px !important;" @click="getCaptchaImage">
                  <img :src="codeImg" :alt="t('login.code')" class="h-full w-full">
                </div>
              </n-input-group>
            </n-form-item>
            <n-button
              type="primary"
              class="w-full h-9 text-[15px] tracking-widest mt-1"
              @click="handleLogin"
            >
              {{ t('login.login') }}
            </n-button>
            <div data-orientation="horizontal" role="none" class="shrink-0 bg-border h-[1px] w-full bg-gray-200 dark:bg-gray-700 mt-6" />
            <div class="text-center mt-3">
              {{ t('login.noAccountQuestion') }}
              <n-a class="text-center" @click="handleSwitchType('register')">
                {{ t('login.goRegister') }}
              </n-a>
            </div>
          </n-form>
          <n-form
            v-else
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            :show-label="false"
            :label-width="0"
            size="large"
          >
            <n-form-item
              path="username"
            >
              <n-input
                v-model:value="registerForm.username"
                :placeholder="t('please.enter', {
                  name: t('login.username'),
                })"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="lucide:user" class="relative top-[-1px] text-zinc-500" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item
              path="email"
            >
              <n-input
                v-model:value="registerForm.email"
                :placeholder="t('please.enter', {
                  name: t('user.wechat'),
                })"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="icon-park-outline:wechat" class="relative top-[-1px] text-zinc-500" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item
              path="password"
            >
              <n-input
                v-model:value="registerForm.password"
                type="password"
                show-password-on="mousedown"
                :placeholder="t('please.enter', {
                  name: t('login.password'),
                })"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="lucide:lock" class="relative top-[-1px]  text-zinc-500" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item
              path="confirmPassword"
            >
              <n-input
                v-model:value="registerForm.confirmPassword"
                type="password"
                show-password-on="mousedown"
                :placeholder="t('login.confirmPassword')"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="lucide:lock" class="relative top-[-1px]  text-zinc-500" />
                </template>
              </n-input>
            </n-form-item>
            <n-form-item
              path="nationality"
            >
              <n-select
                v-model:value="registerForm.nationality"
                :options="nationalityOptions"
                :placeholder="t('please.select', {
                  name: t('user.country'),
                })"
                clearable
              >
                <template #prefix>
                  <SvgIcon name="lucide:earth" class="relative top-[-1px] text-zinc-500" />
                </template>
              </n-select>
            </n-form-item>
            <n-form-item path="code">
              <n-input-group>
                <n-input
                  v-model:value="registerForm.code" :style="{ width: '80%' }" clearable :placeholder="t('please.enter', {
                    name: t('login.code'),
                  })"
                >
                  <template #prefix />
                </n-input>
                <div class="h-[40px] w-[26%] cursor-pointer" style="margin-left: 5px !important;" @click="getCaptchaImage">
                  <img :src="codeImg" :alt="t('login.code')" class="h-full w-full">
                </div>
              </n-input-group>
            </n-form-item>
            <n-button
              type="primary"
              class="w-full h-9 text-[15px] tracking-widest mt-1"
              @click="handleRegister"
            >
              {{ t('login.register') }}
            </n-button>
            <div data-orientation="horizontal" role="none" class="shrink-0 bg-border h-[1px] w-full bg-gray-200 dark:bg-gray-700 mt-6" />
            <div class="text-center mt-3">
              {{ t('login.hasAccountQuestion') }}
              <n-a class="text-center" @click="handleSwitchType('login')">
                {{ t('login.goLogin') }}
              </n-a>
            </div>
          </n-form>
        </div>
      </div>
    </n-card>
  </n-modal>
</template>

<style lang="scss" scoped>
.auth-form-container {
  :deep(.n-form-item-feedback-wrapper){
    min-height: 20px !important;
  }
}
</style>
